package cn.itcast.filter;

import cn.itcast.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
// TODO: 2020/6/25  
/**
 * 登录安全验证
 * 
 */

public class LoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.ServletRequest 无法获取session对象 要转成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //2.会话跟踪,获取session域中的user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        //3.要放行资源的路径
        String sp = request.getServletPath();

        //4.对user进行判断
        if(user != null || "/loginServlet".equals(sp) || "/login.jsp".equals(sp) ){ //要放行的条件,以及资源

            chain.doFilter(request,response);

        }else{//没有登录,跳转到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }


    }
}
